package com.caijg.controller.common;

import com.caijg.domain.vo.Result;
import com.caijg.utils.AliOssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController // ResponseBody + controller
@Slf4j // 记录日志
@Tag(name = "通用模块") // swagger3 控制器标签
@CrossOrigin // 处理跨域问题
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Operation(summary = "图片上传到阿里云oss")
    @PostMapping("/common/img/upload")
    public Result upload(MultipartFile file) throws IOException {

        log.info("文件上传: {}", file);

        // 拿到文件的原始名
        String originalFilename = file.getOriginalFilename();
        // 拿到后缀名
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 制作唯一的文件名
        String objectName = UUID.randomUUID() + extName;

        // 上传文件并返回url
        String url = aliOssUtil.upload(file.getBytes(), objectName);

        // 返回图片url
        return Result.success(url);
    }
}